#!usr/bin/python
# coding=utf-8

import json
import time
import requests

def request_package(model, profile, deploy):
    for count in xrange(3):
        host = "http://corgi.pt.miui.com/open-api/buildRom"
        params = {"user": "xiamin",
                "model": model,
                "profile": profile,
                "deploy": deploy,
                "virant": "default",
                "buildLabel": "today-alpha",
                "enable_miui_debugging": "true"}
        result = requests.post(host, data=params)
        result_json = json.loads(result.text)
        if result_json.get('result') == 'success':
            jobid = result_json.get('id')
            print("JobID: " + str(jobid))
            return jobid
        else:
            print(result_json.get('msg'))
            print 'Jenkins create a job failure. The %s attempt now ...' % str(count + 1)
            continue
    

def check_status(jobid):
    for i in range(180):
        current_status = requests.post("http://corgi.pt.miui.com/open-api/checkBuildStatus",
                                  data={"id": jobid})
        #print(current_status.text)
        result_json = json.loads(current_status.text)
        if result_json.get('status') == 'success':
            url = result_json.get('url')
            print("build rom success ... url: " + url)
            return True, url
        elif result_json.get('status') == 'failure':
            print "build rom failure ... "
            return False, None
        else:
            print("status: " + result_json.get('status'))     
        time.sleep(60)
    print "consume long time ... (180 * 60 seconds)"
    return False, None


if __name__ == "__main__":
    pass
    # # request_package("sagit", "o-dev", "cn")
    # # request_package("sagit", "o-dev", "cn")
    # # request_package("mido", "n-alpha", "cn")
    # # request_package("sagit", "", "cn")
    # check_status(722920)
